package com.gogant.spider.core;

import java.util.Comparator;
import java.util.concurrent.PriorityBlockingQueue;

/**
 * 基于优先级的URL队列
 */
public class PriorityURLQueue implements URLQueue {
    private PriorityBlockingQueue<Context> queue = new PriorityBlockingQueue<Context>(100, new ContextComparator());

    @Override
    public void put(Context context) throws InterruptedException {
        queue.put(context);
    }

    @Override
    public Context take() throws InterruptedException {
        return queue.take();
    }

    @Override
    public int size() {
        return queue.size();
    }

    @Override
    public void clear() {
        queue.clear();
    }

    private class ContextComparator implements Comparator<Context> {
        @Override
        public int compare(Context o1, Context o2) {
            int d = o1.getPriority() - o2.getPriority();
            return d > 0 ? -1 : (d < 0 ? 1 : 0);
        }
    }
}
